package com.wei.lawyer.ui.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.trello.rxlifecycle2.android.ActivityEvent;
import com.wei.lawyer.App;
import com.wei.lawyer.R;
import com.wei.lawyer.model.LawyerBean;
import com.wei.lawyer.model.LawyerChargeBean;
import com.wei.lawyer.model.LawyerCommentBean;
import com.wei.lawyer.net.ApiException;
import com.wei.lawyer.net.presenter.FindPresenter;
import com.wei.lawyer.ui.adapter.BaseAdapter;
import com.wei.lawyer.ui.adapter.BaseDelegateAdapter;
import com.wei.lawyer.ui.adapter.BaseViewHolder;
import com.wei.lawyer.ui.adapter.LawyerCommentAdapter;
import com.wei.lawyer.utils.GiftDialog;
import com.wei.lawyer.utils.RxUtils;

import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;

/**
 * 作者：赵若位
 * 时间：2018/10/30 18:06
 * 邮箱：1070138445@qq.com
 * 功能：律师详情页
 */
public class LawyerActivity extends RootActivity<FindPresenter>
{
    @Bind(R.id.refresh)
    SmartRefreshLayout mRefresh;
    @Bind(R.id.layout_content)
    RecyclerView mRecyclerView;

    /*律师实体对象*/
    private LawyerBean mData;
    private int mPage = 1;//评论页面


    /*布局适配器*/
    private DelegateAdapter mAdapter;
    private BaseDelegateAdapter mDetailAdapter, mChargeAdapter, mCommentTitleAdapter;
    private LawyerCommentAdapter mCommentAdapter;

    /*赠送礼物弹窗*/
    private GiftDialog mGiftDialog;


    @Override
    protected int getLayoutResource()
    {
        return R.layout.activity_lawyer;
    }

    @Override
    protected void setStatusBarColor()
    {

    }

    @Override
    protected FindPresenter createPresenter()
    {
        return new FindPresenter(this, this);
    }

    @Override
    protected void initView(Bundle savedInstanceState)
    {
        super.initView(savedInstanceState);
        setLeftBack();
        setTitle(getString(R.string.tv_lawyer_detail));
        setRefreshListener();
        mData = getIntent().getParcelableExtra(this.getClass().getSimpleName());

        //关闭动效
        ((SimpleItemAnimator) mRecyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mRecyclerView.setItemViewCacheSize(5);
        VirtualLayoutManager mManager = new VirtualLayoutManager(this);
        mManager.setInitialPrefetchItemCount(3);//预取数据
        mRecyclerView.setLayoutManager(mManager);
        mAdapter = new DelegateAdapter(mManager, false);
        mRecyclerView.setAdapter(mAdapter);
        initAdapter();
    }

    /*初始化适配器*/
    private void initAdapter()
    {
        //律师详细资料
        mDetailAdapter = new BaseDelegateAdapter<LawyerBean>(this, R.layout.layout_lawyer_detail)
        {
            @Override
            public void convert(final BaseViewHolder holder, int position, final LawyerBean data)
            {
                holder.setText(data.getNickName(), R.id.item_name)//律师名字
                        .setText(TextUtils.concat(mResources.getString(R.string.tv_worktime), data.getCareerTime()).toString(), R.id.item_workTime)//工作年限
                        .setText(data.getWorkAddress(), R.id.item_address)//工作地址
                        .setText(data.getWorkType(), R.id.item_type)//职业类型
                        .setText(data.getStatus() == 2 ? mResources.getString(R.string.tv_online) :
                                mResources.getString(R.string.tv_outLine), R.id.item_onLine)//当前是否在线
                        .setCircleImageResource(data.getAvatar(), R.dimen.dp_58, R.id.item_heade)
                        .setText(data.getSatisfyRatio2(), R.id.item_ratio)//好评率
                        .setText(String.valueOf(data.getAnswerCount()), R.id.item_commit)//咨询数目
                        .setText(data.getDescription(), R.id.item_descript)//律师说明
                        .setText(getString(R.string.tv_introduction), R.id.item_title);

                /*设置律师在线状态*/
                setLawyerStatus((TextView) holder.getView(R.id.item_onLine), data);

                /*设置律师擅长的标签*/
                String[] label = data.getLabel();
                RecyclerView child = holder.getView(R.id.item_label);
                child.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false));
                BaseAdapter<String> adapter = new BaseAdapter<String>(mActivity, R.layout.item_find_lawyer_label)
                {
                    @Override
                    public void convert(BaseViewHolder holder, int position, String s)
                    {
                        holder.setText(s, R.id.item_title);
                    }
                };
                adapter.bindRecyclerView(child);
                adapter.setData((label == null || label.length == 0) ? null : Arrays.asList(label));
            }

            //设置律师在线状态
            private void setLawyerStatus(final TextView status, final LawyerBean data)
            {
                Observable.create(new ObservableOnSubscribe<Drawable>()
                {
                    @Override
                    public void subscribe(ObservableEmitter<Drawable> e) throws Exception
                    {
                        if (data == null)
                        {
                            Observable.empty();
                        } else
                        {
                            Drawable drawable = mResources.getDrawable(data.getStatus() == 2 ?
                                    R.mipmap.lawyer_online : R.mipmap.lawyer_busy);
                            drawable.setBounds(0, 0,
                                    mResources.getDimensionPixelOffset(R.dimen.dp_11),
                                    mResources.getDimensionPixelOffset(R.dimen.dp_11));
                            e.onNext(drawable);
                            e.onComplete();
                        }
                    }
                }).compose(RxUtils.<Drawable>rxObservableSchedlers())
                        .subscribe(new Consumer<Drawable>()
                        {
                            @Override
                            public void accept(Drawable drawable) throws Exception
                            {
                                status.setCompoundDrawables(drawable, null, null, null);
                            }
                        });
            }
        };
        mAdapter.addAdapter(mDetailAdapter);
        mDetailAdapter.setData(mData);

        //律师收费情况
        mChargeAdapter = new BaseDelegateAdapter<LawyerChargeBean>(this, R.layout.layout_lawyer_charge)
        {
            private int lastPosition = 0;

            @Override
            public void convert(BaseViewHolder holder, final int position, LawyerChargeBean data)
            {
                holder.setImageResource(data.getIconResource(), R.id.item_image)
                        .setText(data.getTitle(), R.id.item_title)
                        .setText(data.getDescript(), R.id.item_descript)
                        .setText("￥" + data.getPrice(), R.id.item_price)
                        .setImageResource(lastPosition == position ? R.mipmap.radio_bg_2 : R.mipmap.radio_bg_1, R.id.item_check)
                        .itemView.setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        if (lastPosition == position) return;
                        lastPosition = position;
                        notifyDataSetChanged();
                    }
                });
            }
        };
        mAdapter.addAdapter(mChargeAdapter);
        mChargeAdapter.setData(LawyerChargeBean.getList(mData));

        //评论标题
        mCommentTitleAdapter = new BaseDelegateAdapter<String>(this, R.layout.layout_home_title)
        {
            @Override
            public void convert(BaseViewHolder holder, int position, String s)
            {
                holder.setText(getString(R.string.tv_comments), R.id.item_title)
                        .setVisible(R.id.item_more, false);
            }
        };
        mAdapter.addAdapter(mCommentTitleAdapter);
        mCommentTitleAdapter.setData("");

        //评论
        mCommentAdapter = new LawyerCommentAdapter(this)
        {
            @Override
            public void setErrorMsg(BaseViewHolder holder)
            {
                holder.setText(getString(R.string.tv_please_login_check), R.id.tv_descript);
                setLoginBtn((TextView) holder.getView(R.id.tv_descript));
            }

            /*设置未登录时候，设置登录按钮的UI情况*/
            private void setLoginBtn(final TextView view)
            {
                Observable.create(new ObservableOnSubscribe<SpannableString>()
                {
                    @Override
                    public void subscribe(ObservableEmitter<SpannableString> e) throws Exception
                    {
                        String descript = mResources.getString(R.string.tv_please_login_check);
                        SpannableString span = new SpannableString(descript);
                        ForegroundColorSpan all = new ForegroundColorSpan(mResources
                                .getColor(R.color.textUnSelected));
                        span.setSpan(all, 0, descript.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);

                        final ForegroundColorSpan login = new ForegroundColorSpan(mResources
                                .getColor(R.color.toast));
                        span.setSpan(login, 1, 3, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);

                        //设置部分文字点击事件
                        ClickableSpan click = new ClickableSpan()
                        {
                            @Override
                            public void updateDrawState(TextPaint ds)
                            {
                                ds.setUnderlineText(false);
                            }

                            @Override
                            public void onClick(View widget)
                            {
                                Intent target = new Intent(mActivity, LawyerActivity.class);
                                target.putExtra(LawyerActivity.class.getSimpleName(), mData);
                                openActivity(LoginActivity.class, target);
                            }
                        };
                        span.setSpan(click, 1, 3, SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
                        e.onNext(span);
                        e.onComplete();
                    }
                }).compose(RxUtils.<SpannableString>rxObservableSchedlers())
                        .compose(mActivity.<SpannableString>bindUntilEvent(ActivityEvent.DESTROY))
                        .subscribe(new Consumer<SpannableString>()
                        {
                            @Override
                            public void accept(SpannableString span) throws Exception
                            {
                                if (view != null)
                                {
                                    view.setText(span);
                                    view.setMovementMethod(LinkMovementMethod.getInstance());
                                    view.setHighlightColor(Color.TRANSPARENT);
                                }
                            }
                        });
            }

        };
        mAdapter.addAdapter(mCommentAdapter);
        mCommentAdapter.setEmptyView(LayoutInflater.from(this).inflate(R.layout.layout_empty, mRecyclerView, false));
        mCommentAdapter.setErrorView(LayoutInflater.from(this).inflate(R.layout.layout_lawyer_nologin, mRecyclerView, false));
    }



    /*设置刷新和加载更多监听*/
    private void setRefreshListener()
    {
        mRefresh.setEnableRefresh(false);
        mRefresh.setOnLoadMoreListener(new OnLoadMoreListener()
        {
            @Override
            public void onLoadMore(RefreshLayout refresh)
            {
                mPage += 1;
                mPresenter.getLawyerDetailComment(mData.getProfileID(), mPage);
            }
        });
    }


    @Override
    protected void initData()
    {
        super.initData();
        mPresenter.getLawyerDetail(mData.getProfileID());
        mPresenter.getLawyerDetailComment(mData.getProfileID(), mPage);
    }


    @OnClick({R.id.tv_gift, R.id.tv_commit})
    public void onViewClicked(View view)
    {
        if (isFastDoubleClick()) return;
        if (TextUtils.isEmpty(App.mToken))
        {
            Intent target = new Intent(mActivity, LawyerActivity.class);
            target.putExtra(LawyerActivity.class.getSimpleName(), mData);
            openActivity(LoginActivity.class, target);
            return;
        }
        switch (view.getId())
        {
            case R.id.tv_gift:
                mGiftDialog = new GiftDialog(this)
                        .setOnClickGiftListener(new GiftDialog.OnClickGiftListener()
                        {
                            @Override
                            public void onClickGiftListener(int price)
                            {
                                alert("价格是：" + price);
                            }
                        });
                mGiftDialog.show();
                break;
            case R.id.tv_commit:
                openActivity(PayActivity.class, null);
                break;
        }
    }


    @Override
    public void showData(Object o)
    {
        super.showData(o);
        if (o instanceof LawyerBean)
        {
            mData = (LawyerBean) o;
            mDetailAdapter.setData(mData);
        }

        if (o instanceof List)
        {
            mCommentAdapter.setError(false);
            List<LawyerCommentBean> list = (List<LawyerCommentBean>) o;
            mCommentAdapter.setData(mCommentAdapter.getData().size(), list);
        }
    }


    @Override
    public void showErrorMsg(String msg)
    {
        mRefresh.setEnableLoadMore(false);
        if (msg.equals(String.valueOf(ApiException.NO_LOGIN)))
        {
            alert(getString(R.string.alert_please_login));
            mCommentAdapter.setError(true);
        }
    }


    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (mGiftDialog != null && mGiftDialog.isShowing())
        {
            mGiftDialog.dismiss();
        }
    }
}
